/*
 * @lc app=leetcode.cn id=606 lang=typescript
 *
 * [606] 根据二叉树创建字符串
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function tree2str(root: TreeNode | null): string {
  let ans = '';
  const _preOrder = (node: TreeNode | null) => {
    if (node === null) return;
    ans += node.val;
    // 如果有右子树，左子树的括号不能省略
    if (node.left !== null || node.right !== null) {
      ans += '(';
      _preOrder(node.left);
      ans += ')';
    }
    if (node.right !== null) {
      ans += '(';
      _preOrder(node.right);
      ans += ')';
    }
  };
  _preOrder(root);
  return ans;
}
// @lc code=end
